import React from "react";
import { toJS } from "mobx";
import { inject, observer } from "mobx-react";
import { withRouter, Route } from "react-router-dom";
import { Base64 } from "js-base64";
import {
  Icon,
  Accordion,
  Tools,
  WhiteSpace,
  PhotoSwipe,
  FilePicker,
  Bubble,
} from "weaver-mobile";
import {
  TabPage,
  SearchAdvanced,
  Reply,
  Comment,
  RouteLayout,
  AtSomeone,
  BrowserHrm,
} from "weaver-mobile-page";
import {
  renderLoading,
  renderNoPermission,
  renderDelete,
  renderIsTop,
  getAttachContent,
  renderNoApprove,
} from "../../public";
import DetailHeader from "./DetailHeader"; // 头部信息
import Participation from "./Participation"; // 参与情况
import RelatedResources from "./RelatedResources"; // 相关资源
import Create from "../Create";
import DetailParticipation from "./DetailParticipation"; // 参与情况
import DetailReadCoverage from "./DetailReadCoverage"; // 参与范围
import { parseQueryString, compareParams } from "../../../util";
import BackTop from "../../../public/back-to-top";
import * as Api from "../../../api/CommunicationApi";
import { isNotData } from "./util";

const getLabel = Tools.getLabel;
const leftConfig = [
  { type: "voice" },
  { type: "blog-biaoqing" },
  { type: "blog-tupian" },
  { type: "@" },
  { type: "tianjia" },
];

@withRouter
@inject("communicationStore")
@observer
export default class Detail extends React.Component {
  static defaultProps = {
    prefixCls: "cowork-communication-detail",
  };

  constructor(props) {
    super(props);
    this.state = {
      path: props.location.pathname || "",
      floor: props.floor || "", // 楼层号
      visible: true,
      showImage: false,
      index: 0,
    };
    this.photoSwipeArr = []; //存放图片预览数组
    this.imgList = []; // Comment列表图片
  }

  componentDidMount() {
    const {
      communicationStore: { detailStore },
      location: { pathname, search },
    } = this.props;
    const { setStoreState, viewCowork, initComment } = detailStore;
    //转化url参数为对象
    const parmsobj = parseQueryString(search);
    let param_id = this.props.coworkId || (parmsobj.id && parmsobj.id);
    let param_floor = this.props.floor || (parmsobj.floor && parmsobj.floor);
    const currentPage = parmsobj.curpage || "relatedCommunication";
    if (
      Tools.mobileDetect().is("iPhone") &&
      window.iNoBounce &&
      window.iNoBounce.isEnabled()
    ) {
      window.iNoBounce.disable(); // 解决ios滑动问题
    }
    setStoreState({
      coworkId: param_id,
      floor: param_floor,
      communicateReplyVisible: this.setDetailReplyVisible,
      path: pathname,
      routePath: pathname,
      page: currentPage,
    });
    viewCowork(param_floor);
    initComment();
    this.getPhotoSwipe();
  }

  // 用来监听从编辑页面跳转过来刷新照片列表
  componentWillReceiveProps(preProps) {
    const {
        history,
        location: { pathname },
      } = preProps,
      { location } = this.props;
    if (
      history.action === "POP" &&
      pathname.indexOf("/detail") > -1 &&
      location.pathname.indexOf("/detail/edit") > -1
    ) {
      this.getPhotoSwipe();
    }
  }

  // 只要有动作就会触发
  componentDidUpdate() {
    this.getPhotoSwipe();
  }

  componentWillUnmount() {
    const {
      communicationStore: { detailStore },
      updateListData,
    } = this.props;
    detailStore.clearInfo();
    updateListData(detailStore.coworkId, { isnew: "0" });

    const { closeAllModel } = detailStore;
    closeAllModel();
    detailStore.setStoreState({
      relatedComment: null,
    });

    if (
      Tools.mobileDetect().is("iPhone") &&
      window.iNoBounce &&
      window.iNoBounce.isEnabled()
    ) {
      window.iNoBounce.enable(); // 解决ios滑动问题
    }
  }

  getPhotoSwipe = () => {
    setTimeout(() => {
      let imgsList = document.getElementsByClassName("wm-comment-content-msg");
      this.imgList = [];
      for (let imgList of imgsList) {
        let imgs = imgList.getElementsByTagName("img");
        for (let img of imgs) {
          this.imgList.push({
            url: img.currentSrc,
            imgId: img.getAttribute("data_id"),
          });
        }
      }
      this.contactArr();
    }, 1000);
  };

  contactArr = () => {
    this.photoSwipeArr = [];
    const {
      communicationStore: { detailStore },
    } = this.props;
    this.photoSwipeArr = [...detailStore.photoArr, ...this.imgList];
  };

  // 图片预览效果点击
  imgOnClick = (e) => {
    if (
      e.target.nodeName === "IMG" &&
      !e.target.className.includes("am-avatar")
    ) {
      let targetIndex = this.getArrIndex(
        this.photoSwipeArr,
        e.target.currentSrc,
        e.target.getAttribute("data_id")
      );
      PhotoSwipe.showImage(this.photoSwipeArr, targetIndex);
    }
  };

  getArrIndex = (Arr, url, id) => {
    let aimIndex = 0;
    Arr.map((v, index) => {
      if (
        toJS(v).imgId === id &&
        (url.indexOf(toJS(v).url) > -1 || url === toJS(v).url)
      ) {
        aimIndex = index;
      }
      return 0;
    });
    return aimIndex;
  };

  // 设置Reply组件的显隐
  setDetailReplyVisible = (val) => {
    const replyRef = this.replyRef;
    if (replyRef) {
      replyRef.setVisible(val, () => {
        if (val) {
          //防止focus的时候，因为获取焦点而自动显示
          replyRef.getInputFocus();
        }
      });
    } else {
      window.setTimeout(() => {
        this.setDetailReplyVisible();
      }, 0);
    }
  };

  // 星标
  isImportant = () => {
    const {
      communicationStore: { detailStore },
    } = this.props;
    detailStore.isImportant
      ? detailStore.coworkMarkItemAsType("normal")
      : detailStore.coworkMarkItemAsType("important");
  };

  // 滚动固定效果
  onScroll = (e) => {
    const {
      communicationStore: { detailStore },
    } = this.props;
    const scrollTop = e.target.scrollTop;
    const tabToTop = document.getElementById("box").offsetTop;
    if (scrollTop >= tabToTop) {
      detailStore.setStoreState({ fixTop: true });
    } else {
      detailStore.setStoreState({ fixTop: false });
    }
  };

  renderHeaderContent = (data) => {
    const { prefixCls } = this.props;
    let content = [];
    if (data.remark !== "") {
      content.push(
        <div
          key="remark"
          className={`${prefixCls}-accordion-content`}
          dangerouslySetInnerHTML={{ __html: data.remark }}
          onClick={(e) => this.imgOnClick(e)}
        />
      );
    }
    if (isNotData(data)) {
      content.push(
        <div className={`${prefixCls}-accordion-attach`} key="attach">
          {getAttachContent(
            "blog-normal",
            data.relateddocList,
            this.operateAttachList
          )}
          {getAttachContent("flow", data.relatedwfList, this.operateAttachList)}
          {getAttachContent(
            "customer",
            data.relatedcusList,
            this.operateAttachList
          )}
          {getAttachContent(
            "xiangmu-o",
            data.mutil_prjsList,
            this.operateAttachList
          )}
          {getAttachContent(
            "task",
            data.relatedprjList,
            this.operateAttachList
          )}
          {getAttachContent(
            "enclosure",
            data.relatedaccList,
            this.operateAttachList
          )}
        </div>
      );
    }
    if (data.remark === "" && !isNotData(data)) {
      content.push(
        <div className="cowork-communication-noMore">
          {getLabel(390851, "您还没有填写相关内容")}~
        </div>
      );
    }
    return content;
  };

  // 页面头部内容
  renderHeader = () => {
    const {
      prefixCls,
      communicationStore: { detailStore },
    } = this.props;
    const {
      detailHeader,
      isImportant,
      defaultShowInfo,
      setStoreState,
    } = detailStore;
    const {
      itemsVO,
      labelBycoworkList,
      canEdit,
      canQuit,
      canApproval,
      canInvite,
      contentSummary,
    } = detailHeader;
    return (
      <div className={`${prefixCls}-header`}>
        <Accordion
          ref="header"
          className={`${prefixCls}-accordion`}
          activeKey={toJS(defaultShowInfo)} // 是否默认打开主题
          onChange={(v) => setStoreState({ defaultShowInfo: v })}
        >
          <Accordion.Panel
            header={
              <DetailHeader
                info={itemsVO}
                label={labelBycoworkList}
                isImportant={this.isImportant}
                isLabel={isImportant}
                canEdit={canEdit}
                canQuit={canQuit}
                canApproval={canApproval}
                canInvite={canInvite}
              />
            }
          >
            <div className={`${prefixCls}-accordion-contentBox`}>
              {itemsVO && this.renderHeaderContent(itemsVO)}
            </div>
          </Accordion.Panel>
        </Accordion>
        {toJS(contentSummary) && (
          <div
            className={`${prefixCls}-header-summary`}
            style={{
              display: defaultShowInfo.length === 0 ? "-webkit-box" : "none",
              WebkitBoxOrient: "vertical",
            }}
            dangerouslySetInnerHTML={{
              __html: Base64.decode(toJS(contentSummary)),
            }}
          />
        )}
      </div>
    );
  };

  openLink = (href) => {
    window.openLink(href);
  };

  operateAttachList = (type, data) => {
    if (type === "enclosure")
      this.openLink(data.url + "?coworkid=" + data.coworkid);
    else this.openLink(data.url);
  };

  // 相关交流 && 与我相关页面
  relatedCommunication = () => {
    const {
      prefixCls,
      communicationStore: { detailStore },
    } = this.props;
    let {
      relatedComment,
      getNextPageDatas,
      hasMore,
      loading,
      relatedMeComment,
      page,
    } = detailStore;
    // 右上角内容渲染
    const renderRightTop = (data) => {
      const {
        communicationStore: { detailStore },
      } = this.props;
      const Curs = "cowork-comment";
      return (
        <div className={`${Curs}-renderRight`}>
          {data.isTop === "1" && renderIsTop}
          {data.cancollect === "1" && (
            <span
              className={`${Curs}-renderRight-collect`}
              onClick={() =>
                detailStore.coworkDiscussOperation(data, "", "collect")
              }
            >
              {data.iscollect === "1" ? (
                <Icon type="blog-concern-hot" color="#f77" size="xs" />
              ) : (
                <Icon type="blog-concern" color="#868686" size="xs" />
              )}
            </span>
          )}
          <span className={`${Curs}-renderRight-floor`}>#{data.floorNum}</span>
        </div>
      );
    };
    const renderTopContent = (data) => {
      const { prefixCls } = this.props;
      return data.needApprove === "1" ? (
        <div className={`${prefixCls}-renderTopContent`}>
          {getLabel(83261, "等待管理员审批")}
        </div>
      ) : (
        ""
      );
    };
    // 没有更多数据效果
    const renderNoMore = (
      <div className={`${prefixCls}-nomore`}>
        <span className={`${prefixCls}-nomore-line-left`} />
        <span className={`${prefixCls}-nomore-line-name`}>
          {getLabel(390064, "没有更多啦")}
        </span>
        <span className={`${prefixCls}-nomore-line-right`} />
      </div>
    );
    // 点击加载下一页效果
    const renderNextPage = (
      <div
        className={`${prefixCls}-nextPage`}
        onClick={() => {
          getNextPageDatas(this.getPhotoSwipe);
        }}
      >
        {loading ? (
          <Icon type="loading" />
        ) : (
          <span>{getLabel(390704, "点击加载下一页")}</span>
        )}
      </div>
    );
    const renderFooter = () => {
      if (hasMore) {
        return renderNextPage;
      } else {
        return renderNoMore;
      }
    };

    return relatedComment && relatedMeComment ? (
      <div
        className={`${prefixCls}-comment`}
        onClick={(e) => this.imgOnClick(e)}
      >
        <Comment
          store={
            page === "relatedCommunication" ? relatedComment : relatedMeComment
          }
          renderRightTop={renderRightTop}
          hasInitialListSize
          renderFooter={renderFooter}
          renderTopContent={renderTopContent}
          operateAttachList={this.operateAttachList}
        />
      </div>
    ) : null;
  };

  //手机端发表图片往内容最后追加
  onImgChange = (datas) => {
    const {
      communicationStore: { detailStore },
    } = this.props;
    let { imagrArr, setStoreState } = detailStore;
    imagrArr = [];
    datas.map((v) => {
      imagrArr.push(`<img src=${v.imgSrc} />`);
      return v;
    });
    setStoreState({ imagrArr: imagrArr });
  };

  onBrowserChange = (key, datas) => {
    const {
      communicationStore: { detailStore },
    } = this.props;
    const { replyDatas, setStoreState } = detailStore;
    if (!replyDatas[key]) {
      replyDatas[key] = datas;
    }
    setStoreState({ replyDatas: replyDatas });
  };

  onUploadChange = (key, datas) => {
    const {
      communicationStore: { detailStore },
    } = this.props;
    const { replyDatas, setStoreState } = detailStore;
    replyDatas[key] = datas;
    setStoreState({ replyDatas: replyDatas });
  };

  invitedHrms = async (...arg) => {
    const {
      communicationStore: { detailStore, onSearch },
    } = this.props;
    const {
      itemsVO,
      getShareConditionStrList,
      viewCowork,
      floor,
    } = detailStore;
    if (!arg[0]) return;
    const params = {
      id: itemsVO.id,
      typeId: itemsVO.typeid,
      shareType: 1,
      shareValue: arg[0],
      shareValuespan: arg[1],
    };
    let res = await Api.saveorupdateCoworkShare(params);
    if (res.flag) {
      Bubble.success(getLabel(30700, "操作成功") + "!", 1);
      onSearch();
      getShareConditionStrList("all");
      viewCowork(floor);
    } else {
      Bubble.error(getLabel("384402", "操作失败，请重试！"));
    }
  };

  setContentValue = (datas) => {
    const {
      communicationStore: { detailStore },
    } = this.props;
    let {
      communicateReply,
      detailReply,
      quoteReply,
      replyType,
      replyComment,
      commentReplyStoreMap,
      quoteReplyStoreMap,
    } = detailStore;
    if (replyComment) {
      detailReply = commentReplyStoreMap[replyComment.replyId];
      quoteReply = quoteReplyStoreMap[replyComment.replyId];
    }
    const replyStore =
      replyType === "quote"
        ? quoteReply
        : replyType === "comment"
        ? detailReply
        : communicateReply;
    const replyRef = this.replyRef;
    if (datas && datas.length > 0) {
      let html = "";
      datas.map((item) => {
        const value = `@${item.name}`;
        // replyRef.replyRef.changeTextValue({
        //   id: item.id,
        //   name: item.name,
        //   value,
        //   len: value.length,
        // }, 'html', true);
        html += `<a contenteditable="false" atsome="@${item.id}" atsome-uid="${item.id}" atsome-name="${item.name}" target="_blank" style="cursor:pointer;text-decoration:none !important;color:#2777c1!important;" href="javascript:void(0)">${value}</a>&nbsp;`;
      });

      replyRef.replyRef.changeTextValue(html);
      replyStore.setState({
        atLists: [...toJS(replyStore.atLists), ...datas],
      });
    }
  };

  renderAt = (item) => {
    const {
      prefixCls,
      communicationStore: { detailStore },
      history,
    } = this.props;
    const { atSomeOne, atSomeOneDatas, getAtConfig, coworkId } = detailStore;
    return (
      <div
        className={`${prefixCls}-atSome`}
        onClick={() => {
          getAtConfig({ coworkId });
          history.push(atSomeOne.path);
        }}
      >
        {item}
        <AtSomeone
          store={atSomeOne}
          datas={toJS(atSomeOneDatas)}
          template={{
            default: [
              {
                key: "col",
                render: (data) => {
                  const { id, name } = toJS(data);
                  return <div key={id}>{name}</div>;
                },
              },
            ],
          }}
          onOk={this.setContentValue}
          searchKey="name"
          imgSrcDataKey="imgSrc"
          nameDataKey="user"
        />
      </div>
    );
  };

  render() {
    const {
      prefixCls,
      communicationStore: { detailStore },
      history,
    } = this.props;
    let {
      setStoreState,
      page,
      detailHeader,
      isLoading,
      relatedAdSearch,
      onRelatedAdSearch,
      publishCowork,
      communicateReply,
      fixTop,
      coworkId,
      isAnonymous,
      viewRight,
      outReplyVisible,
      replyComment,
      commentReplyStoreMap,
      detailReply,
      quoteReply,
      quoteReplyStoreMap,
      onMaskClick,
      replyType,
      placeholderValue,
      saveComment,
      onReset,
      invitedBrowser,
      invitedValueArray,
    } = detailStore;
    const showReply = page === "relatedCommunication" || page === "relatedToMe";
    const __showReply =
      detailHeader &&
      detailHeader.coworkBaseSettingMap &&
      (detailHeader.coworkBaseSettingMap.coworkstate === "0" ||
        detailHeader.coworkBaseSettingMap.coworkstate === "") &&
      detailHeader.itemsVO.status === "2";
    let compare = true;
    if (relatedAdSearch) {
      compare = compareParams(
        toJS(relatedAdSearch.form.formData),
        toJS(relatedAdSearch.form.defaultValues)
      );
    }
    const adType = compare ? "filter-o" : "filter-o-hot";

    if (replyComment) {
      detailReply = commentReplyStoreMap[replyComment.replyId];
      quoteReply = quoteReplyStoreMap[replyComment.replyId];
    }
    const replyStore =
      replyType === "quote"
        ? quoteReply
        : replyType === "comment"
        ? detailReply
        : communicateReply;
    const tabs = [
      { title: getLabel(15153, "相关交流"), key: "relatedCommunication" },
      { title: getLabel(32572, "与我相关"), key: "relatedToMe" },
      { title: getLabel(83274, "参与情况"), key: "participation" },
      { title: getLabel(22672, "相关资源"), key: "relatedResources" },
    ];

    const tabProps = {
      page: page,
      onTabClick: (tab, index) => {
        setStoreState({ page: tab.key });
        //切换交流和与我相关菜单的时候，接口参数受控
        if (tab.key === "relatedCommunication") {
          setStoreState({ recordType: "common", relatedPage: "1" });
        } else if (tab.key === "relatedToMe") {
          setStoreState({ recordType: "relatedme", relatedPage: "1" });
        }
      },
    };
    const rightConfig = { type: "private", text: getLabel(18611, "匿名") };
    const placeholder = () => {
      if (
        replyType === "" &&
        detailHeader.itemsVO &&
        detailHeader.isCoworkTypeApprove === "1"
      ) {
        return getLabel("505825", "交流待审批") + "...";
      } else if (
        replyType === "" &&
        detailHeader.itemsVO &&
        detailHeader.isCoworkTypeApprove !== "1"
      ) {
        return getLabel(390700, "交流内容") + "…";
      } else {
        return placeholderValue;
      }
    };
    const approvalRule =
      detailHeader &&
      detailHeader.itemsVO &&
      detailHeader.itemsVO.approvalAtatus === "1" &&
      detailHeader.canApproval.toString() !== "1";
    if (isLoading) return renderLoading;
    if (approvalRule) {
      return <div style={{ height: "100%" }}>{renderNoApprove}</div>;
    }

    return (
      <div style={{ height: "100%" }}>
        {(!coworkId && renderDelete) || (viewRight === 0 && renderNoPermission)}
        {detailHeader && viewRight > 0 && (
          <div className="cowork-detail-flex">
            <BackTop
              visibilityHeight="200"
              modal
              target="cowork-communication-detail"
            >
              <div
                className={
                  page === "relatedCommunication" &&
                  outReplyVisible &&
                  showReply &&
                  !__showReply
                    ? `${prefixCls} ${prefixCls}-indentation`
                    : prefixCls
                }
                onScroll={this.onScroll}
              >
                {this.renderHeader()}
                <WhiteSpace />
                <div
                  className={
                    fixTop
                      ? `${prefixCls}-touchBox ${prefixCls}-touchBox-fixTop`
                      : `${prefixCls}-touchBox`
                  }
                  id="box"
                >
                  <div id="tabs" className="cowork-fixTop">
                    <TabPage
                      tabs={tabs}
                      btns={
                        page === "relatedCommunication" && [
                          <Icon
                            type={adType}
                            onClick={() => history.push(relatedAdSearch.path)}
                          />,
                        ]
                      }
                      tabProps={tabProps}
                    />
                  </div>
                  <SearchAdvanced
                    store={relatedAdSearch}
                    onSubmit={onRelatedAdSearch}
                    onReset={onReset}
                  />
                  {page === "relatedCommunication" &&
                    this.relatedCommunication()}
                  {page === "relatedToMe" && this.relatedCommunication()}
                  {page === "participation" && <Participation />}
                  {page === "relatedResources" && (
                    <RelatedResources
                      prefixCls={prefixCls}
                      path={this.state.path}
                    />
                  )}
                  <div style={{ display: "none" }}>
                    <BrowserHrm
                      label="人力多选"
                      store={invitedBrowser}
                      hasAdvanceSerach
                      isSingle={false}
                      type={1}
                      valueArray={invitedValueArray}
                      onChange={(...arg) => {
                        this.invitedHrms(...arg);
                      }}
                    />
                  </div>
                </div>
              </div>
            </BackTop>
            {replyStore && showReply && !__showReply && (
              <Reply
                wrappedComponentRef={(ref) => (this.replyRef = ref)}
                store={replyStore}
                placeholder={placeholder()}
                leftConfig={leftConfig}
                rightConfig={isAnonymous === "1" ? rightConfig : ""}
                showOutInput={page === "relatedCommunication" ? true : false}
                visible={false}
                onImgChange={this.onImgChange}
                onBrowserChange={this.onBrowserChange}
                onUploadChange={this.onUploadChange}
                onSubmit={(data) => {
                  replyType === "" ? publishCowork(data) : saveComment(data);
                }}
                onMaskClick={onMaskClick}
                renderAt={this.renderAt}
              />
            )}
            <div style={{ display: "none" }}>
              <FilePicker listType="img" files={this.photoSwipeArr} />
            </div>
          </div>
        )}
        {this.state.path.match(/\/(\S*)/)[1] &&
          this.state.path.match(/\/(\S*)/)[1].split("/")[0] === "detail" && (
            <Route
              key="edit"
              path={`${this.state.path}/edit`}
              render={() => (
                // 编辑协作
                <RouteLayout>
                  <div key="edit" className="wm-route-layout">
                    <Create />
                  </div>
                </RouteLayout>
              )}
            />
          )}
        {
          <Route
            key="detail_participation"
            path={`${this.state.path}/participation`}
            render={() => (
              <RouteLayout>
                <div key="detail_participation" className="wm-route-layout">
                  <DetailParticipation />
                </div>
              </RouteLayout>
            )}
          />
        }
        {
          <Route
            key="detail_coverage"
            path={`${this.state.path}/coverage`}
            render={() => (
              <RouteLayout>
                <div key="detail_coverage" className="wm-route-layout">
                  <DetailReadCoverage coworkId={coworkId} />
                </div>
              </RouteLayout>
            )}
          />
        }
      </div>
    );
  }
}
